//
//  HBFeedbackController.m
//  HeartBeat
//
//  Created by karong on 2023/9/7.
//

#import "HBFeedbackController.h"
#import "HBFeedbackCell.h"

@interface HBFeedbackController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate, HBFeedbackCellDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *listView;

@property (weak, nonatomic) IBOutlet YYTextView *tv;
@property (weak, nonatomic) IBOutlet UILabel *imageCountLabel;
@property (weak, nonatomic) IBOutlet UIButton *feedbackTypeBtn;
@property (nonatomic, strong) GRFeedbackType * selectFeedbackType;
@property (nonatomic, strong) GRFeedbackImage * selectFeedback;
@property (nonatomic, strong) UIImagePickerController * imagePickerController;
@property (nonatomic, strong) NSMutableArray * dataArray;
@property (nonatomic, strong) NSArray * feedbackTypeArray;

@end

@implementation HBFeedbackController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tv.placeholderFont = [UIFont systemFontOfSize:15 weight:(UIFontWeightRegular)];
    self.tv.placeholderTextColor = [UIColor colorFromHexRGB:@"CECECE"];
    self.tv.placeholderText = WSLocalized(@"請輸入你所遇到的詳細問題或建議");
    self.tv.tintColor = UIColor.font_yellow_FFCC00;
    self.tv.textContainerInset = UIEdgeInsetsMake(15, 15, 15, 15);
    [self loadFeedbackTypeRequest];
}

- (void)layoutImageCount {
    self.imageCountLabel.text = SF(@"%@(%ld/3)", WSLocalized(@"添加圖片"), self.dataArray.count - 1);
}

- (void)loadFeedbackTypeRequest {
    [HBRequest loadFeedbackTypeWithSuccess:^(NSArray *array) {
        if (array.count > 0) {
            self.selectFeedbackType = array.firstObject;
        }
        self.feedbackTypeArray = array;
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (void)submitRequest {
    NSMutableString * imageStr = [NSMutableString new];
    for (GRFeedbackImage * feedbackImage in self.dataArray) {
        if (feedbackImage.type == 2) {
            if (imageStr.length > 0) {
                [imageStr appendString:@","];
            }
            [imageStr appendString:feedbackImage.imageUrl];
        }
    }
    WeakSelf
    [HBRequest submitFeedbackWithOpinion:self.tv.text type:self.selectFeedbackType?self.selectFeedbackType.id:0 images:imageStr success:^{
        [HBToast simple:WSLocalized(@"感謝您的反饋，我們會盡快處理")];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (IBAction)feedbackTypeAction:(id)sender {
    [ViewManager showPickerAlterWithTitle:WSLocalized(@"選擇反饋類型")dataArray:self.feedbackTypeArray selectHandle:^(id obj) {
        self.selectFeedbackType = obj;
    } inController:self];
}

- (IBAction)submitAction:(id)sender {
    if (KIsNullOrEmpty(self.tv.text)) {
        [HBToast simple:WSLocalized(@"請描述遇到的問題或建議")];
        return;
    }
    [self submitRequest];
}

#pragma mark UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return MIN(self.dataArray.count, 3);
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HBFeedbackCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HBFeedbackCell" forIndexPath:indexPath];
    cell.delegate = self;
    [cell setDataWithObject:self.dataArray[indexPath.row]];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(75, 75);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    self.selectFeedback = self.dataArray[indexPath.row];
    self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:self.imagePickerController animated:YES completion:nil];
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info {
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        GRFeedbackImage * feedback;
        if (self.selectFeedback.type == 0) {
            feedback = [GRFeedbackImage new];
            feedback.type = 1;
            feedback.image = image;
            [self.dataArray insertObject:feedback atIndex:self.dataArray.count-1];
        }
        else {
            feedback = self.selectFeedback;
            feedback.image = image;
        }
        [self layoutImageCount];
        [self.listView reloadData];
        [HBRequest uploadImage:image success:^(NSString *string) {
            feedback.type = 2;
            feedback.imageUrl = string;
        } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
            
        }];
    }];
    
}

#pragma mark HBFeedbackCellDelegate
- (void)feedbackCellDelAction:(id)object {
    NSIndexPath * indexPath = [self.listView indexPathForCell:object];
    [self.dataArray removeObjectAtIndex:indexPath.row];
    [self layoutImageCount];
    [self.listView reloadData];
}


- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        GRFeedbackImage * feedback = [GRFeedbackImage new];
        feedback.type = 0;
        feedback.image = IMG(@"icon_jj");
        _dataArray = [[NSMutableArray alloc]init];
        [_dataArray addObject:feedback];
    }
    return _dataArray;
}

- (UIImagePickerController *)imagePickerController {
    if (!_imagePickerController) {
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.delegate = self;
        _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        _imagePickerController.allowsEditing = YES;
    }
    return _imagePickerController;
}

- (void)setSelectFeedbackType:(GRFeedbackType *)selectFeedbackType {
    _selectFeedbackType = selectFeedbackType;
    [self.feedbackTypeBtn setTitle:selectFeedbackType.name forState:(UIControlStateNormal)];
}

@end
